package com.wt.demo;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * readWriteLock和lock的使用，注意看两种情况执行结束的时间
 * 读读：非阻塞
 * 读写：阻塞
 * 写写：阻塞
 * @author: wangtao
 * @date:17:44 2019/6/13
 * @email:386427665@qq.com
 */
public class ThreadReadWriteLock {
    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock lock = new ReentrantLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();
    private int value;

    public int handleRead(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return -1;
        } finally {
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, int v) {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ThreadReadWriteLock demo = new ThreadReadWriteLock();
        Runnable read = () -> {
            demo.handleRead(readLock);
//                demo.handleRead(lock);
        };
        Runnable write = () -> {
            demo.handleWrite(writeLock, new Random().nextInt());
//            demo.handleWrite(lock, new Random().nextInt());
        };

        long t = System.currentTimeMillis();
        for (int i = 0; i < 18; i++) {
            new Thread(read).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(write).start();
        }
    }

}
